<template>
    <!-- 文章列表 -->
    <div class="article-list-blo">
        <div class="server_title">
            <div class="crumbs store_title">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item>文章管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="mainBtn">
                <el-button type="success" @click="addArticle()">
                    <i class="el-icon-plus"></i>添加文章
                </el-button>
                <!--<el-button type="info"><i class="el-icon-delete"></i>垃圾箱</el-button>-->
            </div>
        </div>
        <div class="article-content">
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column prop="viceTitle" label="副标题" align="center"></el-table-column>
                <el-table-column prop="date" label="操作时间"></el-table-column>
                <el-table-column label="封面图" align="center">
                    <template slot-scope="scope">
                        <a v-if="scope.row.coverId" style="cursor: pointer" @click="handlePictureCardPreview(scope.$index, scope.row)">查看图片</a>
                        <span v-else>无</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" @click="editFun(scope.row, scope.$index)">修改</el-button>
                        <el-button size="small" type="danger" @click="delFun(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination :current-page.sync="page.current" @current-change="handleoneCurrentChange" @size-change="handleoneSizeChange" layout="total, prev, pager, next" :total="page.total" :page-size="page.size" :current-page="page.current"></el-pagination>
            </div>
        </div>
        <!-- 添加或修改文章 -->
        <el-dialog :title="optTitle" :visible.sync="articleEditDialog" width="1460px" top="5vh" class="editor-dialog-blo">
            <div class="article-deit-block">
                <div class="article-deit-blo">
                    <el-form label-width="80px" :model="form" :rules="rules" ref="ruleForm">
                        <el-form-item label="标题" prop="title">
                            <el-input v-model="form.title"></el-input>
                        </el-form-item>
                        <el-form-item label="副标题" prop="subTitle">
                            <el-input v-model="form.subTitle"></el-input>
                        </el-form-item>
                        <el-form-item label="封面图" prop="imageUrl">
                            <el-upload class="avatar-uploader" action :on-change="onUploadChange" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :auto-upload="false">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="权值" prop="priorty">
                            <el-input v-model="form.priorty" style="width: 300px;"></el-input>
                        </el-form-item>
                        <div class="ueditor-blo">
                            <label class="label">内容</label>
                            <div class="value">
                                <div id="editor"></div>
                            </div>
                        </div>
                        <el-form-item label="html文本">
                            <el-input type="textarea" v-model="form.htmlText" style="width: 300px;"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="articleEditDialog = false">取 消</el-button>
                        <el-button type="success" @click="previewFun">预 览</el-button>
                        <el-button v-if="optTitle == '新增文章'" type="primary" @click="submitForm()">新 增</el-button>
                        <el-button v-else type="primary" @click="submitForm()">保 存</el-button>
                    </span>
                </div>
                <!-- 手机预览 -->
                <div class="mobile-blo">
                    <iframe id="mobileIframe" name="mobileIframe" src="./static/newDetail/newDetail.html">
                        <p>您的浏览器不支持 iframe 标签。</p>
                    </iframe>
                    <!-- <div class="preview-btn">
                        <el-button type="primary" @click="submitForm()">预 览</el-button>
                    </div>-->
                </div>
            </div>
        </el-dialog>
        <!--查看图片-->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
        </el-dialog>
    </div>
</template>

<script>
import {
    articlesList,
    addArticles,
    editArticles,
    delArticles,
    attachments
} from "../api/api"
import { getFormatDate } from "../tool/tool"
import { base64, tool_confirm } from "../tool/tool"

import Editor from "wangeditor"

export default {
    data() {
        return {
            editor: null,
            optTitle: "新增",
            articleEditDialog: false,
            updateId: "",
            tableData: [],
            imageUrl: "",
            //图片
            fileList: [],
            /* 分页 */
            page: {
                current: 0,
                size: 10,
                total: 0
            },

            dialogVisible: false,
            dialogImageUrl: "",
            form: {
                title: "",
                subTitle: "",
                priorty: "",
                coverId: "",
                htmlText: "",
            },
            rules: {
                title: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "blur"
                    }
                ],
                subTitle: [
                    {
                        required: true,
                        message: "请输入副标题",
                        trigger: "blur"
                    }
                ],
                priorty: [
                    {
                        required: true,
                        message: "请输入权值",
                        trigger: "blur"
                    }
                ]
            },
            config: {
                initialFrameWidth: null,
                initialFrameHeight: 350
            }
        }
    },
    created() {},
    computed: {},
    mounted() {
        this.getArticlesList()

        // this.editor.addListener("ready", function() {
        //     _this.editor.setContent(_this.defaultMsg) // 确保UE加载完成后，放入内容。
        // })
    },
    methods: {
        // 分页导航
        handleoneCurrentChange(val) {
            this.page.current = val
            this.getArticlesList()
            // this.readHua(val - 1)
        },
        handleoneSizeChange(val) {
            // console.log(val,111111)
        },
        submitForm() {
            this.$refs["ruleForm"].validate(valid => {
                if (valid) {
                    this.saveArticle()
                } else {
                    this.$message({
                        message: "表单验证失败，请审对你的表单数据",
                        type: "warning"
                    })
                    return false
                }
            })
        },
        getArticlesList() {
            let current = this.page.current == 0 ? 0 : this.page.current - 1
            //获取文章列表
            articlesList({ page: current, size: this.page.size }).then(res => {
                console.log(res)
                let listData = res.data.content.page.content
                for(let i in listData){
                    listData[i].date = getFormatDate(listData[i].createdTime, "yyyy-MM-dd hh:mm:ss")
                }
                this.tableData = listData
                this.page.total = res.data.content.page.totalElements
                console.log(this.tableData)
            })
        },
        /* 实例编辑器 */
        initEditor() {
            if (!this.editor) {
                this.editor = new Editor("#editor")
                this.editor.customConfig.uploadImgServer =
                    this.$ajaxBase + "/system/ueditor/imgUpload"
                this.editor.customConfig.uploadFileName = "file"
                this.editor.customConfig.uploadImgHooks = {
                    customInsert: function(insertImg, result, editor) {
                        var url = result.url
                        insertImg(url)
                        // result 必须是一个 JSON 格式字符串！！！否则报错
                    }
                }
                this.editor.create()
            }
            this.resetPreview()
        },
        /* 新增文章 */
        addArticle() {
            this.optTitle = "新增文章"
            this.articleEditDialog = true
            setTimeout(() => {
                this.initEditor()
            }, 50)
        },
        /* 修改文章 */
        editFun(row) {
            this.optTitle = "修改文章"
            this.updateId = row.id
            this.articleEditDialog = true
            setTimeout(() => {
                this.initEditor()
                console.log(row)
                this.form = {
                    title: row.title,
                    subTitle: row.viceTitle,
                    priorty: row.priorty,
                    coverId: row.coverId
                }
                if (row.coverId) {
                    this.imageUrl =
                        this.$ajaxBase +
                        "/attachments/download?id=" +
                        row.coverId
                }

                let content = JSON.parse(JSON.stringify(row.content))
                this.setUEContent(this.base64_decode(content))
            }, 50)
        },
        /* 保存文章 */
        saveArticle() {
            console.log(this.getUEContent())
            if (!this.form.coverId) {
                this.$message.warning("清先上传封面图！")
                return false
            }
            let htmlText = (this.form.htmlText)? this.form.htmlText : this.getUEContent()
            let data = {
                title: this.form.title,
                viceTitle: this.form.subTitle,
                priorty: this.form.priorty,
                articleType: "STRATEGY",
                coverId: this.form.coverId,
                content: this.base64_encode(htmlText)
            }
            let hostFun =
                this.optTitle == "修改文章" ? editArticles : addArticles
            if (this.optTitle == "修改文章") {
                data.id = this.updateId
            }
            hostFun(data).then(res => {
                console.log(data)
                if (this.optTitle == "修改文章") {
                    this.$message.success("修改成功！")
                    this.getArticlesList()
                    this.articleEditDialog = false
                } else {
                    this.$message.success("新增成功！")
                    this.getArticlesList()
                    this.articleEditDialog = false
                }
            })
        },
        /* 删除文章 */
        delFun(row) {
            console.log(row)
            this.$confirm("此操作将永久删除该文章, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                delArticles(row).then(res => {
                    this.$message.success("删除成功!")
                    this.getArticlesList()
                })
            })
        },
        /* 预览文章 */
        previewFun() {
            let htmlText = (this.form.htmlText)? this.form.htmlText : this.getUEContent()
            let data = {
                title: this.form.title,
                viceTitle: this.form.subTitle,
                image: this.imageUrl,
                content: htmlText
            }
            mobileIframe.window.previewData(data)
        },
        /* 重置弹窗信息 */
        resetPreview() {
            this.form = {
                title: "",
                subTitle: "",
                priorty: ""
            }
            this.imageUrl = ""
            this.setUEContent("")
            let data = {
                title: "",
                viceTitle: "",
                image: "",
                content: ""
            }
            setTimeout(() => {
                mobileIframe.window.previewData(data)
            }, 100)
        },
        /* 获取富文本的内容 */
        getUEContent() {
            return this.editor.txt.html()
        },
        /* 设置富文本内容 */
        setUEContent(content) {
            this.editor.txt.html(content)
        },
        //上传图片事件
        onUploadChange(file) {
            let that = this
            let base64Url = base64(file.url)

            base64Url.then(function(url) {
                let str = url.split(",")
                // console.log(str[1])
                attachments(str[1]).then(res => {
                    that.form.coverId = res.data.content.imgId
                    that.imageUrl =
                        that.$ajaxBase +
                        "/attachments/download?id=" +
                        res.data.content.imgId
                })
            })
        },
        handlePictureCardPreview(e, val) {
            // storeAsGet("/banners?id=" + val.id).then(res => {
            //     console.log(res, "id")
            console.log(val)
            this.dialogImageUrl =
                this.$ajaxBase + "/attachments/download?id=" + val.coverId
            this.dialogVisible = true
            // })
        },
        /* 图片上传块 */
        handleAvatarSuccess(res, file) {
            console.log(res)
            this.form.coverId = this.id
            this.imageUrl = URL.createObjectURL(file.raw)
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg"
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!")
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!")
            }
            return isJPG && isLt2M
        },

        base64_encode(val) {
            var str = CryptoJS.enc.Utf8.parse(val)
            var base64 = CryptoJS.enc.Base64.stringify(str)
            return base64
        },
        base64_decode(val) {
            var words = CryptoJS.enc.Base64.parse(val)
            return words.toString(CryptoJS.enc.Utf8)
        }
    },
    destroyed() {
        this.editor.destroy()
    }
}
</script>

<style>
.editor-dialog-blo .article-deit-block {
    width: 100%;
    display: flex;
    align-content: center;
    justify-content: space-between;
}
.editor-dialog-blo .mobile-blo {
    height: 100%;
    padding: 64px 16px;
    box-sizing: border-box;
    width: 365px;
    background-image: url("/static/img/phone.png");
    background-repeat: no-repeat;
    background-size: 100%;
}
.article-deit-blo {
    width: calc(100% - 380px);
}
#mobileIframe {
    width: 100%;
    height: 580px;
    background-color: #fff;
}

.article-list-blo .server_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 18px;
}
.article-list-blo .ueditor-blo {
    /* display: flex;
    align-items: center; */
    margin-bottom: 20px;
}
.article-list-blo .ueditor-blo .value {
    position: relative;
    margin-left: 80px;
}
.article-list-blo .ueditor-blo .label {
    width: 68px;
    text-align: right;
    float: left;
}
.article-list-blo .dialog-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader .el-upload--text {
    width: 296px;
    height: 148px;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 296px;
    height: 148px;
    line-height: 148px !important;
    text-align: center;
}
.avatar {
    width: 296px;
    height: 148px;
    display: block;
}
</style>
